<template>
    <div>
      <el-dialog :visible.sync="addTalentDialog" :title="title" top="10px" center :before-close="handleClose">
        <div
            style="height:200px;display: flex;flex-direction: column;align-items: center;margin-top: 15px;justify-content: space-around;">
          <div style="margin-bottom: 20px;">
            <el-upload
            v-if="addTalentDialog"
             class="upload-demo"
             :action="`${$apiHost}/img/fileImgUrl`"
             :on-preview="handlePreview"
             :on-remove="handleRemove"
             :before-remove="beforeRemove"
              :on-success="onSuccess"
              :before-upload="beforeAvatarUpload"
             :limit="1"
             accept=".docx"
             :on-exceed="handleExceed"
            >
             <el-button size="small" type="primary">点击上传</el-button>
             <div slot="tip" class="el-upload__tip">只能上传docx文件，且不超过20MB</div>
          </el-upload>
          </div>
          <div style="display: flex;align-items: center;">
            <span style="white-space: nowrap; "><i style="color: red">*</i>合同金额：</span>
            <el-input size="small" v-model="money" ></el-input>
          </div>
          <div slot="tip" class="el-upload__tip">输入金额必须和合同金额保持一致！</div>
        </div>
        <span slot="footer">
          <el-button style="color: #FFFFFF" @click="submit" :loading="loading">提 交</el-button>
          <el-button style="color: #343a40;background-color:#e0e0e0;" @click="addTalentDialog=false">取 消</el-button>
        </span>
      </el-dialog>
     
    </div>
  </template>
  <script>
  import axios from "axios";
  import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
  import AMapLoader from "@amap/amap-jsapi-loader";
  
  export default {
    name: "contract",
    components: {
      Editor,
      Toolbar
    },
    data() {
      return {
        loading:false,
        assignTaskId:0,
        contractId:0,
        fileList: '',
        money:null,
        loc: {
          longitude: '',
          latitude: ''
        },
        address: "",
        marker: null,
        autocomplete: null,
        placeSearch: null, //搜索框
        keyword: '',
        searchResult: [],
        isShowResult: false,
        certificateImg: [],
        addTalentDialog: false,
        openMap: false,
        title: "上传合同",
        form: {
          introduction: "暂无简介",
          userName: "",
          sex: "",
          phoneNumber: "",
          age: "",
          password: "",
          address: "",
          idCard: "",
          wechatId: "",
          roleId: "",
          workYears: "",
        },
        talentRole: [],
        upImage: [],
        upImageList: [],
        imageUrl: [],
        frontImg: '',
        AMap: null,
        map: null,
        backImg: '',
        editUsrId: '',
        avatarUrl: '',
        editor: null,
        html: '',
        toolbarConfig: {},
        mode: 'default',
        projectDetail: [
          {
            startTime: "",
            endTime: "",
            content: "",
            projectName: "",
          }
        ]
      }
    },
  
    computed: {
      headers() {
        const token = window.$quinn.getStorage("tokenv3")
        return {
          token,
        };
      }
    },
    created() {
      document.addEventListener('paste', this.handlePaste)
    },
    mounted() {
    },
    unmounted() {
      this.map?.destroy();
    },
    methods: {
      handleClose(){
        this.addTalentDialog = false
        this.fileList=''
        this.money=null
      },
        submit(){
          if(this.loading){
            return  this.$message.warning(`请勿重复提交`);
          }
          if(!this.money.length){
            return  this.$message.warning(`金额未输入`);
          }
          if(!this.fileList.length){
            return  this.$message.warning(`合同未上传`);
          }
          this.loading=true
            this.$api.contractUploadNoSignContract({
                assignTaskId:this.assignTaskId,
				        inputImg:this.fileList,
                money:this.money
            }).then(res => {
              if(res){
                this.$emit('submitContract')
                this.$message.success("上传成功！")
                this.addTalentDialog = false
                this.fileList=''
                this.money=null
              }
              this.loading=false
         }).catch(err=>{
          this.loading=false
         })
        },
        beforeAvatarUpload(file) {
          const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
          const isSizeValid = file.size / 1024 / 1024 <= 20; // 文件大小限制为 20MB

          // 检查文件类型
          if (!isDocx) {
            this.$message.error('只能上传 .docx 文件');
            return false; // 阻止上传
          }
        
          // 检查文件大小
          if (!isSizeValid) {
            this.$message.error('文件大小不能超过 20MB');
            return false; // 阻止上传
          }
        
          return true; // 允许上传
      },
        onSuccess(res) {
          if (res.code == 200&&res.result.length) {
             this.fileList = res.result[0];
            // value.push(res.data.url);
            // value.push(res.data)
            // this.$emit("change", value);
          }
     },
        handleRemove(file, fileList) {
          this.fileList=''
        // console.log(file, fileList);
      },
      handlePreview(file) {
        // console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },

      deleteCer(i) {
        this.certificateImg.splice(i, 1)
      },
      handlePaste(event) {
        if (!this.addTalentDialog) return;
        const clipboardData = event.clipboardData || window.clipboardData;
        if (clipboardData) {
          for (let i = 0; i < clipboardData.items.length; i++) {
            const item = clipboardData.items[i];
  
            if (item.kind === 'file' && item.type.startsWith('image/')) {
              const file = item.getAsFile();
              if (file) {
                this.uploadImage(file);
              }
            } else {
              this.$message.error('请拷贝图片!');
              break;
            }
          }
        }
      },
      uploadImage(imageFile) {
        const formData = new FormData();
        formData.append('file', imageFile);
        axios.post(`${this.$apiHost}/img/fileImgUrl`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'token': window.$quinn.getStorage("tokenv3")
          }
        })
            .then(response => {
              this.certificateImg.push(response.data.result[0]);
            })
            .catch(error => {
            });
      },
      handleClick() {
        this.map.on('click', (e) => {
          let lng = e.lnglat.lng
          let lat = e.lnglat.lat
          let marker = new AMap.Marker({
            position: new AMap.LngLat(lng, lat)
          })
          this.map.clearMap()// 清除所有覆盖物（点标志）
          this.map.add(marker)// 添加点标志
          let lnglat = [lng, lat]
          let that = this
          that.geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
              that.address = result.regeocode.formattedAddress;
              that.showInfoWindow(marker);//自定义信息窗体
              let thisPosition = {
                address: that.address,
                lng: lng,
                lat: lat
              };
              that.$emit("select", thisPosition)
            } else {
              that.$message.error('根据经纬度查询地址失败')
            }
          })
          this.loc.latitude = lat
          this.loc.longitude = lng
        })
      },
      showInfoWindow(marker) {
        let infoWindow = new AMap.InfoWindow({
          isCustom: true, //是否自定义信息窗体
          content: `<div style="background-color: white;padding: 0 5px; border-radius: 5px;border: 1px solid #cccccc;"> 地址：${this.address}</div>`,
          closeWhenClickMap: true,
          zIndex: 999,
          offset: new AMap.Pixel(16, -35)
        });
        infoWindow.open(this.map, marker.getPosition());
      },
      handleClickResult(e) {
        const {location, district, address} = e
        const {lng, lat} = location || {}
        // 1. 如果当前搜索结果有经纬度, 直接在地图上选中, 并返回当前的值
        if (lng && lat) {
          this.map.clearMap() //先清空点位
          this.changeValue(lng, lat, e.name, district + address)
          this.keyword = district + address
        } else {
          this.isShowResult = false
          this.placeSearch.search(district + address);
        }
      },
      // 输入框搜索显示下拉
      searchByKeyword() {
        this.autocomplete.search(this.keyword, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.searchResult = result.tips.map((item) => {
              return {
                ...item,
                address: Array.isArray(item.address) ? (item.address[0] || '') : item.address
              }
            })
            this.isShowResult = true
          }
        })
      },
      // // 点击地图
      // initMarket(name) {
      //   if (!(this.loc.longitude && this.loc.latitude)) {
      //     return
      //   }
      //   this.isShowResult = false
      //   if (this.map.getAllOverlays('marker').length) {
      //     // 地图已有标注，清除标注
      //     this.map.clearMap();
      //   }
      //   this.marker = new AMap.Marker({
      //     icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      //     position: [this.loc.longitude, this.loc.latitude],
      //     offset: new AMap.Pixel(-10, -26),
      //     zIndex: 102
      //   })
      //   this.showInfoWindow(this.marker);//自定义信息窗体
      //   if (name) {
      //     let num = name.length * 4
      //     marker.value.setLabel({
      //       offset: new AMap.value.Pixel(-num, 35),
      //       content: name
      //     })
      //   }
      //   this.map.add(this.marker)
      // },
      initAMap() {
        AMapLoader.reset()
        AMapLoader.load({
          key: "eaec2470d19b92bbe95753e566dfda1d",             //Key
          version: "2.0",
          plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.MarkerClusterer', 'AMap.DistrictSearch', 'AMap.ZoomControl', 'AMap.Polygon', 'AMap.Geocoder',],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap) => {
          this.geocoder = new AMap.Geocoder()
          this.map = new AMap.Map("container", {  //设置地图容器id
            // viewMode: "3D",    //是否为3D地图模式
            resizeEnable: true,
            zoom: 12,           //初始化地图级别
            center: [112.938814, 28.228209], //初始化地图中心点位置
          });
          this.handleClick(AMap)//地图选点
          // this.map.on('click', (e) => {
          //   this.loc.latitude = e.lnglat.lat
          //   this.loc.longitude = e.lnglat.lng
          //   this.initMarket()
          // })
          var autoOptions = {
            input: "tipinput"
          };
          this.autocomplete = new AMap.AutoComplete(autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            map: this.map
          });
        }).catch(e => {
          // console.log(e);
        })
      },
      changeValue(longitude, latitude, name, address) {
        this.isShowResult = false
        this.loc.longitude = longitude
        this.loc.latitude = latitude
        const center = new AMap.LngLat(longitude, latitude);
        // 将地图的中心点移动到指定的经纬度
        this.map.setCenter(center);
        this.marker = new AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: [this.loc.longitude, this.loc.latitude],
          zIndex: 103
        })
        this.map.add(this.marker)
      },
      sureSelPoint() {
        if (this.loc.latitude && this.loc.longitude) {
          this.openMap = false
          this.form = {...this.form, address: this.address || this.keyword};
        } else {
          this.$message.warning('请选择经纬度')
        }
      },
     
      onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      },
      handleOpen(row) {
        if(row.status>1){
          this.addTalentDialog = true
          this.assignTaskId=row.assignTaskId
          this.contractId=row.contractId
        }else{
          this.$message.warning('当前任务状态无法上传合同，请测量完成后再上传！')
        }

       
      },
      openMapDia() {
        this.initAMap();
        this.openMap = true
      },
      deletePic(i) {
        this.upImage.splice(i, 1)
      },
      handleChangePic(file, fileList) {
        if (fileList.length > 1) {
          fileList.splice(0, 1);
          this.certificateImg = fileList
        }
      },
      handleChangeFont(res, fileList) {
        this.frontImg = res.result[0];
      },
      handleChangeBack(res, fileList) {
        this.backImg = res.result[0];
      },
      // handleAvatarSuccess(res, file) {
      //   this.imageUrl.push(res.data.result[0])
      //   console.log(this.imageUrl)
      // },
      handleAvatar(res, file) {
        this.avatarUrl = res.result[0];
      },
      addExperience(val) {
        this.projectDetail.push({
          startTime: "",
          endTime: "",
          content: "",
          projectName: ""
        })
      },
      deleteExperience(index) {
        this.projectDetail.splice(index, 1)
      },
      submitTalent() {
        const data = {
          ...this.form,
          projectDetail: this.projectDetail,
          frontImg: this.frontImg,
          backImg: this.backImg,
          avatar: this.avatarUrl,
          certificateImg: [this.certificateImg],
          longitude: this.loc.longitude,
          latitude: this.loc.latitude
        }
        this.$api.talentInsertPcTalent(data).then(res => {
          if (res == 1) {
            this.$emit('addStatus', 1);
            this.$message.success("添加成功！")
            this.addTalentDialog = false
          }
        })
      },
      editTalent() {
        const data = {
          ...this.form,
          projectDetail: this.projectDetail,
          frontImg: this.frontImg,
          backImg: this.backImg,
          avatar: this.avatarUrl,
          certificateImg: this.certificateImg,
          longitude: this.loc.longitude,
          latitude: this.loc.latitude,
          userId:this.editUsrId
        }
        this.$api.talentUpdateTalent(data).then(res => {
          if (res == 1) {
            this.$emit('addStatus', 1);
            this.$message.success("编辑成功！")
            this.addTalentDialog = false
          }
        })
      }
    }
  }
  </script>
  <style src="@wangeditor/editor/dist/css/style.css"></style>
  <style scoped lang="less">
  #container {
    width: 100%;
    height: 500px;
  }
  
  ::v-deep .el-dialog__body {
    padding: 0px 20px !important;
  }
  
  .mapBox {
    position: relative;
  
    .searchBox {
      position: absolute;
      z-index: 111;
      top: 10px;
      left: 10px;
    }
  }
  
  .search-result {
    width: 100%;
    max-height: 300px;
    overflow-y: scroll;
    background-color: #fff;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.0600);
    box-sizing: border-box;
  
    .result-item {
      width: 100%;
      cursor: pointer;
      border-bottom: 2px solid #eee;
      padding: 10px 12px;
  
      .area-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        height: 20px;
        color: rgba(0, 0, 0, 0.65);
        font-size: 14px;
        line-height: 20px;
      }
  
      .area-address {
        color: rgba(0, 0, 0, 0.4500);
        font-size: 12px;
        line-height: 18px;
      }
    }
  }
  
  .avatar-uploader {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  .content {
    width: 90%;
    margin-top: 10px;
    display: flex;
    align-items: center;
  
    .el-input, .el-select {
      margin-right: 30px;
    }
  }
  
  .box-card {
    min-height: 200px;
  
  }
  </style>